import React, {
	PureComponent
} from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Table, Button, Card, Modal, Form, Icon, Input, Menu, Dropdown, message,InputNumber, TreeSelect, Select, Switch, Row, Col, DatePicker, Upload,TimePicker, } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import StandardTable from '../../components/StandardTable';
import styles from '../Mana/Role.less';
import ReactDOM from 'react-dom';
// 引入编辑器以及编辑器样式
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/braft.css';

//课程包管理 -admin 单独
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;
const FormItem = Form.Item;
const { TextArea } = Input;
var school_select = []; //学校
var school_name = [];  //查询条件中的学校

var course_select = []; //父级课程
var disableds = true; //默认禁用
var ages = []; //起止年龄

var courseSelect = []; //包含的课程默认查询
var coursePage_select = []; //父级课程包
var fetch_coursePageselect=[];
var effectiveDateRules = []; //销售时间是否必选
//默认状态
var state;
//时间戳 转化为时间格式
var Y, M, D, h, m, s = "";

function timestampToTime(timestamp) {
	var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000   //* 1000
	Y = date.getFullYear() + '/';
	M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
	D = date.getDate() + ' ';
	h = date.getHours() + ':';
	m = date.getMinutes() + '-';
	s = date.getSeconds();
	return Y + M + D;
}

function timestamps(timestamp){
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000   //* 1000
    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';
    m = date.getMinutes() + '-';
    s = date.getSeconds();
    return m+s;
}

//选择类型 a.b.c，父级是否可选择
function courseTypeChange(value) {
	if(value == 2) {
		disableds = false;
		coursePage_select=fetch_coursePageselect;
	} else {
		disableds = true;
		coursePage_select = [];
	}
}
//起止年龄
function agesOnChange(value) {
	ages = value.split(",");
}

function validityOnChage(value) {
	if(value != 1) {
		effectiveDateRules = [{
			required: true,
			message: '销售时间不能为空!'
		}]
	} else {
		effectiveDateRules = "";
	}
}

//图片
var headerimg = "";
var imageUrl = "";
//图片
function getBase64(img, callback) {
	const reader = new FileReader();
	reader.addEventListener('load', () => callback(reader.result));
	reader.readAsDataURL(img);
}
//图片封面
class Avatar extends React.Component {
	state = {
		loading: false
	};
	handleChange = (info) => {
		if(info.file.status === 'uploading') {
			this.setState({
				loading: true
			});
			return;
		}
		if(info.file.status === 'done') {
			headerimg = info.file.response.obj.path;
			imageUrl = info.file.response.obj.path;
			getBase64(info.file.originFileObj, imageUrl => this.setState({
				imageUrl,
				loading: false,
			}));
		}
	}
	render() {
		const uploadButton = (
			<div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
		);
		if(imageUrl == undefined) {
			imageUrl = this.state.imageUrl;
		} else {
			headerimg = imageUrl;
		}
		const urls = "api/web/attachment/upload.manage?token=" + sessionStorage.getItem('token');
		return(
			<Upload
        name="file"
        style={{width:'200px'}}
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action={urls}
        method="POST"
        enctype="multipart/form-data"
        onChange={this.handleChange}
      >
        {imageUrl ? <img src={imageUrl} alt=""  style={{width:'200px'}} /> : uploadButton}
      </Upload>
		);
	}
}


/*按钮 -点击弹出富文本框*/
class AvatarButton extends React.Component {
  state = { visible: false }
  showModal = () => {
    this.setState({
      visible: true,
    });
  }
  handleOk = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  }
  handleCancel = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  }
  render() {
    return (
      <div>
        <Button type="primary" onClick={this.showModal}>编辑内容</Button>
        <Modal
        maskClosable={false}
      	  destroyOnClose={true}
          title="描述内容"
          width="90%"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
         <Demo/>
        </Modal>
      </div>
    );
  }
}

var contents = ""; //富文本框
class Demo extends React.Component {
	render() {
		const editorProps = {
			height: 500,
			contentFormat: 'html',
			initialContent: contents,
			onChange: this.handleChange,
			media: {
				allowPasteImage: true, // 是否允许直接粘贴剪贴板图片（例如QQ截图等）到编辑器
				image: true, // 开启图片插入功能
				video: false, // 开启视频插入功能
				audio: false, // 开启音频插入功能
				validateFn: null, // 指定本地校验函数，说明见下文
				uploadFn: this.uploadFns, // 指定上传函数，说明见下文
				removeConfirmFn: null, // 指定删除前的确认函数，说明见下文
				onRemove: null, // 指定媒体库文件被删除时的回调，参数为被删除的媒体文件列表(数组)
				onChange: null, // 指定媒体库文件列表发生变化时的回调，参数为媒体库文件列表(数组)
				onInsert: null, // 指定从媒体库插入文件到编辑器时的回调，参数为被插入的媒体文件列表(数组)
			},
		}
		return(
			<div className="demo">
        <BraftEditor {...editorProps}/>
      </div>
		)
	}
	handleChange = (content) => {
		contents = content;
	}
	uploadFns = (param) => {
		const serverURL = "api/web/attachment/upload.manage?token=" + sessionStorage.getItem('token');
		const xhr = new XMLHttpRequest
		const fd = new FormData();
		// libraryId可用于通过mediaLibrary示例来操作对应的媒体内容
		const successFn = (response) => {
			// 假设服务端直接返回文件上传后的地址
			// 上传成功后调用param.success并传入上传后的文件地址
			param.success({
				url: JSON.parse(xhr.response).obj.path
			});
		}
		const progressFn = (event) => {
			// 上传进度发生变化时调用param.progress
			param.progress(event.loaded / event.total * 100)
		}
		const errorFn = (response) => {
			// 上传发生错误时调用param.error
			param.error({
				msg: 'unable to upload.'
			})
		}
		xhr.upload.addEventListener("progress", progressFn, false)
		xhr.addEventListener("load", successFn, false)
		xhr.addEventListener("error", errorFn, false)
		xhr.addEventListener("abort", errorFn, false)
		fd.append('file', param.file)
		xhr.open('POST', serverURL, true)
		xhr.send(fd)
	}
}

const CreateForm = Form.create()(props => {
	const {
		modalVisible,
		form,
		handleAdd,
		handleModalVisible,
		title,
		obj
	} = props;
	const {
		getFieldDecorator
	} = form;
	const okHandle = () => {
		form.validateFields((err, fieldsValue) => {
			if(err) return;
			if(fieldsValue.parentId == undefined) fieldsValue.parentId = "" //父级
			if(fieldsValue.state == undefined) fieldsValue.state = "1" //状态
			if(fieldsValue.upDownState == undefined) fieldsValue.upDownState = "0" //上下架状态
			if(fieldsValue.type == undefined) fieldsValue.type = "2" //课程类型
			if(fieldsValue.hotState == undefined) fieldsValue.hotState = "0" //热门
			if(fieldsValue.newState == undefined) fieldsValue.newState = "0" //最新
			if(fieldsValue.sequence == undefined) fieldsValue.sequence = "" //
			if(fieldsValue.discountPrice == undefined) fieldsValue.discountPrice = "" //折扣价
			if(fieldsValue.activeNumber == undefined) fieldsValue.activeNumber = "" //有效次数
			if(fieldsValue.validity == undefined) fieldsValue.validity = "" //是否长期有效
			if(fieldsValue.schoolId == undefined) {
				fieldsValue.schoolId = "";
			}
			if(fieldsValue.courseId != undefined) {
				fieldsValue.courseId = fieldsValue.courseId.join(",");
			} else {
				fieldsValue.courseId = "";
			}
			if(fieldsValue.salesDate!=undefined){
				fieldsValue.salesStartDate = timestampToTime(fieldsValue.salesDate[0]); //销售开始时间
				fieldsValue.salesEndDate = timestampToTime(fieldsValue.salesDate[1]); //销售结束时间
			}else{
				delete fieldsValue.salesStartDate;
				delete fieldsValue.salesEndDate;
				delete fieldsValue.salesEndDate;
			}
			if(fieldsValue.effectiveDate != undefined) {
				fieldsValue.effectiveStartDate = timestampToTime(fieldsValue.effectiveDate[0]); //有效开始时间
				fieldsValue.effectiveEndDate = timestampToTime(fieldsValue.effectiveDate[1]); //有效结束时间
			}

			var ages=timestamps(fieldsValue.fitAge);
			console.log(ages);
			console.log("============");
			if(ages!=undefined){
				var arr=ages.split("-");
				fieldsValue.fitAge=arr[0];
	  			fieldsValue.endAge=arr[1];
			}else{
  				fieldsValue.fitAge="";
  				fieldsValue.endAge="";
			}

			fieldsValue.coverPicture=headerimg;
			fieldsValue.description=contents.replace(/\#/g, '$aoxin');
			form.resetFields();
			handleAdd(title, obj.coursePageId, fieldsValue);
		});
	};
	return(
		<Modal
      maskClosable={false}
      destroyOnClose={true}
      width={'60%'}
      title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false,'','')}
    >
    	<Form layout="horizontal">
	      	<FormItem label="课程包" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
	            {getFieldDecorator('name', {
	            	initialValue:obj.name,
	              rules: [{ required: true, message: '课程名称不能为空!' }],
	            })(<Input  placeholder="请输入课程包名称"/>)}
      		</FormItem>
      		<FormItem label="状态" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('state', {
            		initialValue:obj.state==undefined ? "1":obj.state,
            	})(<Select placeholder="请选择状态">
             			<Option value="1">有效</Option>
			            <Option value="0">无效</Option>
			        </Select>)}
          	</FormItem>
	        <FormItem label="是否长期有效"  labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('validity', {
            		initialValue:obj.validity==undefined ? "1":obj.validity,
            	})(<Select placeholder="请选择是否长期有效">
             			<Option value="1">是</Option>
			            <Option value="0">否</Option>
			        </Select>)}
          	</FormItem>
          	<FormItem label="父级" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('parentId',{
            		initialValue:obj.parentId,
            	})(<Select allowClear placeholder="请选择父级" >
								{coursePage_select}</Select> )}
          	</FormItem>
          	<FormItem label="起止年龄" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('fitAge', {
            		initialValue:obj.fitAge==undefined ? moment('3-6','mm-ss'): moment(obj.fitAge,'mm-ss') ,//obj.fitAge,moment('08-23','mm-ss')
            		rules: [{ required: true, message: '起止年龄不能为空!' }],
            	})(<TimePicker  format={"mm-ss"} allowEmpty inputReadOnly placeholder="请选择起止年龄" style={{width:'100%'}}/>
			       )}
          	</FormItem>
          	<FormItem label="学校" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('schoolId', {
	            	initialValue:obj.schoolId,
	            	rules: [{ required: true, message: '学校不能为空!' }],
	            })(<Select allowClear placeholder="请选择学校"  >
					{school_select}
				</Select> )}
          	</FormItem>
          	<FormItem label="包含的课程" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('courseId', {
			          initialValue:obj.courseId,
			          rules: [{ required: true, message: '课程不能为空!' }],
			        })(<Select  mode="tags"  mode="multiple" allowClear placeholder="请选择课程" >
					{courseSelect}
					</Select> )}
          	</FormItem>

          	<FormItem label="销售时间" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            	{getFieldDecorator('salesDate', {
            		initialValue:obj.salesDate,
            		//rules: effectiveDateRules,
            		rules: [{ required: true, message: '销售时间不能为空!' }],
            	})(<RangePicker showTime  format="YYYY-MM-DD HH:mm:ss" style={{width:'100%'}}   onChange={validityOnChage}/>)}
          	</FormItem>

          	<FormItem label="上下架" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('upDownState', {
            		initialValue:obj.upDownState==undefined ? "1":obj.upDownState,
            	})(<Select placeholder="请选择上下架">
             			<Option value="1">上架</Option>
			            <Option value="0">下架</Option>
			        </Select>)}
          	</FormItem>

          	<FormItem label="排序" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('sequence', {
            		initialValue:obj.sequence,
            	})(<InputNumber   placeholder="默认置顶" style={{width:'100%'}}  />)}
          	</FormItem>
          	<FormItem label="有效次数" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('activeNumber', {
            		initialValue:obj.activeNumber,
            	})(<Input placeholder="请输入有效次数"/>)}
          	</FormItem>
          	<FormItem label="原价" labelCol={{span: 8}}  wrapperCol={{span: 12}}  className={styles.w50left}>
            	{getFieldDecorator('price', {
            		initialValue:obj.price,
            		rules: [{ required: true, message: '价格不能为空!' }],
            	})(<Input placeholder="请输入原价"/>)}
          	</FormItem>
          	<FormItem label="实际价格" labelCol={{span: 8}}  wrapperCol={{span: 12}}  className={styles.w50left}>
            	{getFieldDecorator('discountPrice', {
            		initialValue:obj.discountPrice,
					rules: [{ required: true, message: '价格不能为空!' }],
            	})(<Input placeholder="请输入实际价格"/>)}
          	</FormItem>
          	<FormItem label="是否热门" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('hotState', {
            		initialValue:obj.hotState==undefined ? "0":obj.hotState,
            	})(<Select placeholder="请选择是否热门">
             			<Option value="1">是</Option>
			            <Option value="0">否</Option>
			        </Select>)}
          	</FormItem>
          	<FormItem label="是否最新" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('newState', {
            		initialValue:obj.newState==undefined ? "1":obj.newState,
            	})(<Select placeholder="请选择是否最新">
             			<Option value="1">是</Option>
			            <Option value="0">否</Option>
			        </Select>)}
          	</FormItem>
          	 <FormItem label="简介"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('briefIntroduction', {
            	rules: [{ required: true, message: '简介不能为空!' }],
            	initialValue:obj.briefIntroduction,
            })(
              	<TextArea></TextArea>
            )}
        </FormItem>
          	<FormItem label="封面图片" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {(<Avatar />)}
	        </FormItem>
          	<FormItem label="描述" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('description', {
	            	initialValue:obj.description,
	            })(<AvatarButton />)}
          	</FormItem>
    	</Form>
    </Modal>
	);
});

@connect(({
	campucoursepage,
	loading,
	menu
}) => ({
	campucoursepage,
	loading: loading.models.campucoursepage,
	threeMenu: menu.threeMenu,
}))
@Form.create()
export default class TableList extends PureComponent {
	state = {
		modalVisible: false,
		selectedRows: [],
		formValues: {},
		obj: "",
	};
	componentDidMount() {
		/*按钮查询*/
		/*this.props.dispatch({
			type: 'menu/fetch_three_menu',
		});*/
		//默认查询table 数据
		this.props.dispatch({
			type: 'campucoursepage/fetch_coursePage',
			payload: {
				state :1,
			},
		});

		//默认查询 学校 select
		this.props.dispatch({
			type: 'campucoursepage/fetch_ListByschoolselect',
			callback: (res, data) => {
				school_select = [];
				school_name = [];
				for(let i = 0; i < data.length; i++) {
					school_select.push(<Option key={data[i].id}>{data[i].value}</Option>);
					school_name.push(<Option key={data[i].id}>{data[i].value}</Option>);
				}
			}
		});
		//查询课程
		this.props.dispatch({
			type: 'campucoursepage/fetchId_course',
			callback: (res, data) => {
				courseSelect = [];
				for(let i = 0; i < data.length; i++) {
					//courseSelect.push(<Option key={data[i].courseId}><span className={styles.courseName}>{data[i].name}</span><span className={styles.courseName}>{data[i].remark}</span><span  className={styles.courseName}>{data[i].price}</span></Option>);
					courseSelect.push(<Option key={data[i].courseId}>{data[i].name}</Option>);
				}
			},
		});
	}
	//分页查询
	handleStandardTableChange = (pagination, filtersArg, sorter) => {
		const {
			dispatch
		} = this.props;
		const {
			formValues
		} = this.state;
		const filters = Object.keys(filtersArg).reduce((obj, key) => {
			const newObj = { ...obj
			};
			newObj[key] = getValue(filtersArg[key]);
			return newObj;
		}, {});
		const params = {
			currentPage: pagination.current,
			pageSize: pagination.pageSize,
			...formValues,
			...filters,
		};
		if(sorter.field) {
			params.sorter = `${sorter.field}_${sorter.order}`;
		}
		dispatch({
			type: 'campucoursepage/fetch_coursePage',
			payload: params,
		});
	};
	handleSelectRows = rows => {
		this.setState({
			selectedRows: rows,
		});
	};

	/*重置*/
	handleFormReset = () => {
		const {
			form,
			dispatch
		} = this.props;
		form.resetFields();
		this.setState({
			formValues: {},
		});
		dispatch({
			type: 'campucoursepage/fetch_coursePage',
		});
	}
	/*查询*/
	handleSearch = e => {
		e.preventDefault();
		const {
			dispatch,
			form
		} = this.props;
		form.validateFields((err, fieldsValue) => {
			if(err) return;
			const values = { ...fieldsValue,
			};
			this.setState({
				formValues: values,
			});
			if(values.name == undefined){
				values.name = ""
			}
			if(values.name == undefined) {
				values.name = ""
			}
			if(values.courseType == undefined) {
				values.courseType = "2"
			}
			if(values.upDownState == undefined) {
				values.upDownState = ""
			}
			if(values.newState == undefined) {
				values.newState = ""
			}
			if(values.hotState == undefined) {
				values.hotState = ""
			}
			if(values.state == undefined) {
				values.state = ""
			}
			if(values.type == undefined) {
				values.type = ""
			}
			if(values.schoolId == undefined) {
				values.schoolId = ""
			}

			dispatch({
				type: 'campucoursepage/fetch_coursePage',
				payload: { ...values
				},
			});
		});
	};
	/*弹窗*/
	handleModalVisible = (flag, record, title) => {
		const {
			selectedRows
		} = this.state;
		contents = "";
		imageUrl = "";
		effectiveDateRules = "";
		if(flag == false) {
			this.setState({
				modalVisible: false,
			});
		} else {
			var obj = {};
			if(title == "新建") {
				//默认查询 父级课程包 select
				this.props.dispatch({
					type: 'campucoursepage/fetch_coursePageselect',
					callback: (res, data) => {
						fetch_coursePageselect=[];
						coursePage_select = [];
						for(let i = 0; i < data.length; i++) {
							coursePage_select.push(<Option key={data[i].coursePageId}>{data[i].name}</Option>);
						}
						fetch_coursePageselect=coursePage_select;
					}
				});
				this.setState({
					modalVisible: !!flag,
					title: title,
					obj: obj,
				});
			} else {
				if(record == undefined || Object.keys(selectedRows).length == 0) {
					message.info("还未选择项");
				} else if(Object.keys(selectedRows).length > 1) {
					message.info("只可选择一项");
				} else {
					var data = selectedRows[0];
					this.props.dispatch({
						type: 'campucoursepage/fetch_coursePagese_courselect',
						payload: {
							coursePageId: data.coursePageId
						},
						callback: (res, datas) => {
							if(data.courseId != Array) {
								data.courseId = [];
							}
							if(res == 1) {
								for(let i = 0; i < datas.length; i++) {
									data.courseId.push(datas[i].course_id + '');
								}
							}
							if(data.effectiveStartDate != undefined) {
								data.effectiveDate = [moment(data.effectiveStartDate), moment(data.effectiveEndDate)];
							} else {
								data.effectiveDate = [];
							}
							if(data.salesStartDate!=undefined){
								data.salesDate = [moment(data.salesStartDate), moment(data.salesEndDate)];
							}
							if(data.schoolId != Array) {
								data.schoolId  =  typeof data.schoolId=="string"? data.schoolId.split(","):data.schoolId;
							}
							if(data.type != undefined) { //课程类型
								data.type += ''
							}
							if(data.state != undefined) { //状态
								data.state += ''
							}
							if(data.upDownState != undefined) { //上下架状态
								data.upDownState += ''
							}
							if(data.parentId != undefined) { //父级
								data.parentId += ''
							}
							if(data.hotState != undefined) { //是否热门
								data.hotState += ''
							}
							if(data.newState != undefined) { //是否最新
								data.newState += ''
							}
							if(data.validity != undefined) { //是否长期有效
								data.validity += ''
								if(data.validity != 1) {
									effectiveDateRules = [{
										required: true,
										message: '销售时间不能为空!'
									}]
								} else {
									effectiveDateRules = "";
								}
							} else {

								effectiveDateRules = "";
							}
							if(data.description!= undefined) {
								contents = data.description.replace(/\$aoxin/g, '#');
							} else {
								contents = "";
							}
							data.fitAge=data.fitAge+"-"+data.endAge;
							contents=data.description.replace(/\$aoxin/g, '#');
							imageUrl=data.coverPicture;
							data.courseId=data.courseId;
							this.setState({
								modalVisible: true,
								title: title,
								obj: data,
							});
						},
					});

				}
			}
		}
	};
	/*新增,修改*/
	handleAdd = (title, Id, fields) => {
		if(title == "新建") {
			this.props.dispatch({
				type: 'campucoursepage/add_coursePage',
				payload: { ...fields,
				},
				callback: (res, resMsg) => {
					if(res == 1) {
						message.success(resMsg);
						this.setState({})
					} else {
						message.error(resMsg);
					}
				},
			});
		} else if(title == "编辑") {
			this.props.dispatch({
				type: 'campucoursepage/edit_coursePage',
				payload: {
					...fields,
					coursePageId: Id,
				},
				callback: (res, resMsg) => {
					this.state.selectedRows=[];
					if(res == 1) {
						message.success(resMsg);
					} else {
						message.error(resMsg);
					}
				},
			});
		}
		this.setState({
			modalVisible: false,
		});
	};

	/*删除*/
	confirmModel = (title, Id) => {
		console.log(title);
		const {
			dispatch
		} = this.props;
		const {
			selectedRows
		} = this.state;
		if(Id == undefined && Object.keys(selectedRows).length == 0) {
			message.info("还未选择项");
		} else {
			var Ids = [];
			if(Id != undefined) {
				Ids = Id;
			} else if(selectedRows != null) {
				Ids.push(selectedRows.map(row => row.coursePageId).join(','));
			}
			if(title != "删除") {
				var state;
				if(title == "禁用") {
					state = 0;
				} else {
					state = 1;
				}
				Modal.confirm({
					title: '是否' + title + '选中项状态?',
					okText: '确定',
					cancelText: '取消',
					onOk() {
						/*批量修改状态*/
						dispatch({
							type: 'campucoursepage/disabled_coursePage',
							payload: {
								coursePageIds: Ids,
								state: state,
							},
							callback: (res, resMsg) => {
								if(res == 1) {
									message.success(resMsg);
								}else{
									message.error(resMsg);
								}
							},
						});
					}
				});
			} else {
				Modal.confirm({
					title: '是否删除当前数据选中',
					content: '',
					onOk() {
						dispatch({
							type: 'campucoursepage/remove_school',
							payload: {
								coursePageIds: Ids,
							},
							callback: (res, resMsg) => {
								if(res == 1) {
									message.success(resMsg);
								} else {
									message.error(resMsg);
								}
							},
						});
					},
				});
			}
		}
	}
	renderSimpleForm() {
		const {
			getFieldDecorator
		} = this.props.form;
		return(
			<Form onSubmit={this.handleSearch} layout="inline">
		        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
		           <Col md={8} sm={24}>
			            <FormItem label="课程名称">
			              	{getFieldDecorator('name')(
			                <Input placeholder="请输入" />
			              )}
			            </FormItem>
		          	</Col>

		          	<Col md={8} sm={24}>
			            <FormItem label="上下架状态">
			              	{getFieldDecorator('upDownState')(
			                <Select placeholder="请选择" style={{ width: '100%' }}>
	             				<Option value="1">上架</Option>
				            	<Option value="0">下架</Option>
			                </Select>
			              )}
			            </FormItem>
		          	</Col>
		          	<Col md={8} sm={24}>
			            <FormItem label="是否最新">
				            {getFieldDecorator('newState')(
				                <Select placeholder="请选择" style={{ width: '100%' }}>
				                  <Option value="1">是</Option>
				                  <Option value="0">否</Option>
				                </Select>
				            )}
			            </FormItem>
		          	</Col>
		        </Row>
		        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
			        <Col md={8} sm={24}>
			            <FormItem label="是否热门">
			              	{getFieldDecorator('hotState')(
			                <Select placeholder="请选择" style={{ width: '100%' }}>
			                 	<Option value="1">是</Option>
		                  		<Option value="0">否</Option>
			                </Select>
			              	)}
			            </FormItem>
		          	</Col>
					<Col md={8} sm={24}>
			            <FormItem label="状态">
			              	{getFieldDecorator('state')(
			                <Select placeholder="请选择" style={{ width: '100%' }}>
			                 	<Option value="1">有效</Option>
		                  		<Option value="0">无效</Option>
			                </Select>
			              	)}
			            </FormItem>
		          	</Col>
		          	<Col md={8} sm={24}>
			            <FormItem label="所属学校">
			              	{getFieldDecorator('schoolId')(
			                <Select placeholder="请选择" style={{ width: '100%' }} >
			                 	{school_name}
			                </Select>
			              	)}
			            </FormItem>
		          	</Col>
				 </Row>
				<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
		            <Col md={24} sm={24}>
			            <FormItem>
				            <span style={{ float: 'right', marginBottom: 24 }}>
				            <Button type="primary" htmlType="submit">查询</Button>
				            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
				            </span>
			            </FormItem>
		          	</Col>
		        </Row>
		    </Form>
		);
	}
	render() {
		const {
			campucoursepage: {
				data
			},
			loading,
			threeMenu
		} = this.props;
		const {
			selectedRows,
			modalVisible,
			title,
			obj
		} = this.state;
		const columns = [{
			title: '序号',
			dataIndex: 'coursePageId',
			key: 'coursePageId',
			render: (text, record, index) => {
				return index + 1
			}
		}, {
			title: '课程包名称',
			dataIndex: 'name',
			key: 'name',
		}, {
			title: '价格',
			dataIndex: 'price',
			key: 'price',
		}, {
			title: '折扣价',
			dataIndex: 'discountPrice',
			key: 'discountPrice',
		},{
			title: '状态',
			dataIndex: 'state',
			key: 'state',
			render: (text, record, index) => {
				if(record.state == 1) return "有效"
				else if(record.state == 0) return "无效"
			}
		}, {
			title: '所属学校',
			dataIndex: 'schoolName',
			key: 'schoolName',
		}];
		const parentMethods = {
			handleAdd: this.handleAdd,
			handleModalVisible: this.handleModalVisible,
			confirmModel: this.confirmModel,
			validityOnChage: this.validityOnChage,
		};
		return(
			<PageHeaderLayout title="课程系统/课程包管理">
			<Card bordered={false}>

	          <div className={styles.tableList}>
	            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
	            <span>
	            	{!threeMenu.new && <Button type="primary" onClick={() => this.handleModalVisible(true,'','新建')} style={{ marginLeft: 8 }}>新建</Button>}
	            	{!threeMenu.edit && <Button type="primary"  onClick={() => this.handleModalVisible(true,'','编辑')} style={{ marginLeft: 8 }}>编辑</Button>}
				   { /*{!threeMenu.delete && <Button type="primary" onClick={() => this.confirmModel('删除')} style={{ marginLeft: 8 }}>删除</Button>}*/}
				    <Button type="primary"  onClick={() => this.confirmModel('启用')} style={{ marginLeft: 8 }}>启用</Button>
				   <Button type="ghost"  onClick={() => this.confirmModel('禁用')} style={{ marginLeft: 8 }}>禁用</Button>
	            </span>
	            <StandardTable
	              selectedRows={selectedRows}
	              loading={loading}
	              data={data}
	              columns={columns}
	              onSelectRow={this.handleSelectRows}
	              onChange={this.handleStandardTableChange}
	            />
	          </div>

	        <CreateForm {...parentMethods} modalVisible={modalVisible} title={title} obj={obj}/>
	      </Card>
	       </PageHeaderLayout>
		);
	}
}
